import 'dart:io';
import 'dart:ui';

import 'package:fijkplayer/fijkplayer.dart';
import 'package:fish_redux/fish_redux.dart';

import 'rtmp_action.dart';
import 'rtmp_state.dart';

Effect<RtmpState> buildEffect() {
  return combineEffects(<Object, Effect<RtmpState>>{
    RtmpAction.action: _onAction,
    Lifecycle.initState: _onInit,
    Lifecycle.dispose: _onDispose,
  });
}

void _onAction(Action action, Context<RtmpState> ctx) {
}
void _onInit(Action action, Context<RtmpState> ctx) {
  var state = ctx.state;
  if (state.player == null) {
    state.player = FijkPlayer();


    var realPlayUrl = 'rtmp://58.200.131.2:1935/livetv/cctv1';


    state.player.setDataSource(realPlayUrl,
        autoPlay: true, showCover: true);
  }
}

void _addVideoListener(RtmpState state) {
  if (state.player?.state == FijkState.prepared) {
    state.player.seekTo(state.lastInMilliseconds ?? 0);
  }
}
void _onDispose(Action action, Context<RtmpState> ctx) {
  if (Platform.isAndroid) _unbindBackgroundIsolate();
  _destoryFijkPlayer(ctx.state);
}

void _unbindBackgroundIsolate() {
  IsolateNameServer.removePortNameMapping('downloader_send_port');
}

void _destoryFijkPlayer(RtmpState state) {
  state.player?.release();
  state.player = null;
}
